package com.qianyucc.blog.service;

import cn.hutool.core.bean.*;
import cn.hutool.core.bean.copier.*;
import com.qianyucc.blog.mapper.*;
import com.qianyucc.blog.model.dto.*;
import com.qianyucc.blog.model.entity.*;
import com.qianyucc.blog.model.enums.*;
import com.qianyucc.blog.model.vo.*;
import com.qianyucc.blog.utils.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;

import java.util.*;
import java.util.stream.*;

import static com.qianyucc.blog.global.Constants.*;

/**
 * @author lijing
 * @date 2019-10-13 10:55
 * @description 与评论相关的业务
 */
@Service
public class CommentService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 插入评论
     *
     * @param commentDTO 要插入的评论
     */
    public void insComment(CommentDTO commentDTO) {
        CommentDO commentDO = new CommentDO();
        BeanUtil.copyProperties(commentDTO, commentDO);
        commentDO.setLikes(0L);
        commentDO.setGmtCreate(System.currentTimeMillis());
        commentDO.setGmtUpdate(commentDO.getGmtCreate());
        commentMapper.insComment(commentDO);
    }

    /**
     * 根据文章的id查询该文章的所有评论
     *
     * @param articleId 文章id
     * @return 评论列表
     */
    public List<CommentVO> findCommentByArticleId(String articleId) {
        List<CommentDO> commentDOS = commentMapper.findByArticleId(articleId);
        List<CommentVO> commentVOS = commentDOS.stream()
                .filter(commentDO -> commentDO.getType() == 1)
                .map(commentDO -> {
                    UserDO userDO = userMapper.findById(commentDO.getCommentator());
                    return CommentVO.create(commentDO, userDO);
                }).collect(Collectors.toList());
        // 查找所有一级评论对应的二级评论
        commentVOS.forEach(commentVO -> {
            List<CommentVO> secondary = commentDOS.stream()
                    .filter(commentDO -> commentDO.getType() == 2 &&
                            commentDO.getParentId().equals(commentVO.getId()))
                    .map(commentDO -> {
                        UserDO userDO = userMapper.findById(commentDO.getCommentator());
                        CommentVO vo = CommentVO.create(commentDO, userDO);
                        vo.setComments(0L);
                        return vo;
                    })
                    .collect(Collectors.toList());
            commentVO.setSecondLevelComments(secondary);
            commentVO.setComments((long) secondary.size());
        });
        return commentVOS;
    }

    /**
     * 返回所有评论
     *
     * @param pageNumber 页码
     * @return 一页评论
     */
    public PageInfoVO<CommentItemVO> findAllComments(Integer pageNumber) {
        Map<String, Object> QUERY_MAP = queryMap();
        if (pageNumber > 1) {
            QUERY_MAP.put("offset", (pageNumber - 1) * (DEFAULT_PAGE_SIZE));
        }
        List<CommentDO> commentDOS = commentMapper.pageComment(QUERY_MAP);
        ArrayList<CommentItemVO> commentItemVOS = new ArrayList<>();
        for (CommentDO commentDO : commentDOS) {
            CommentItemVO commentItemVO = new CommentItemVO();
            BeanUtil.copyProperties(commentDO, commentItemVO, CopyOptions.create().ignoreNullValue());
            // 评论者
            UserDO userDO = userMapper.findById(commentDO.getCommentator());
            if (userDO != null) {
                commentItemVO.setCommentatorName(userDO.getName());
            } else {
                commentItemVO.setCommentatorName(UserType.ANONYMOUS.getName());
            }
            commentItemVO.setGmtUpdate(Utils.formatDate(commentDO.getGmtUpdate(), DEFAULT_DATE_TIME_PATTERN));
            if (commentDO.getType() == 1) {
                ArticleDO a = articleMapper.findById(commentDO.getArticleId());
                if (a != null) {
                    commentItemVO.setParent(a.getTitle());
                    commentItemVO.setArticleId(a.getId());
                }
            } else {
                CommentDO c = commentMapper.findById(commentDO.getParentId());
                if (c != null) {
                    commentItemVO.setParent(c.getContent());
                    commentItemVO.setArticleId(c.getArticleId());
                }
            }
            commentItemVOS.add(commentItemVO);
        }
        Long count = commentMapper.count();
        int totalPages = (int) (count % DEFAULT_PAGE_SIZE == 0 ? count / DEFAULT_PAGE_SIZE : count / DEFAULT_PAGE_SIZE + 1);
        return PageInfoVO.create(pageNumber, totalPages, count, commentItemVOS);
    }

    /**
     * 根据id删除评论
     *
     * @param id 要删除的评论的id
     */
    public void deleteById(Long id) {
        HashMap<String, Object> paraMap = new HashMap<>();
        CommentDO commentDO = commentMapper.findById(id);
        if (commentDO.getType().equals(CommentType.FIRST_LEVEL.getFlag())) {
            // 删除该该评论的同时，还要删除该评论下的二级评论
            paraMap.put("parentId", id);
            paraMap.put("type", 2);
            List<CommentDO> childComments = commentMapper.findByParentIdAndType(paraMap);
            for (CommentDO c : childComments) {
                commentMapper.deleteById(c.getId());
            }
        }
        commentMapper.deleteById(id);
    }
}
